package jwtutil

import (
	"errors"
	"github.com/golang-jwt/jwt/v5"
	"ruoyi/config"
	"ruoyi/utils/log"
	"time"
)

// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImJhciIsImlzcyI6ImFjeSIsInN1YiI6ImxvZ2luIiwiZXhwIjoxNzQyMjA2OTA5LCJuYmYiOjE3NDE3NzQ5MDksImlhdCI6MTc0MTc3NDkwOX0.hdIIVOjc9-fcWSKXpf-_Q3M_axq44HxdJYySe2TcBrc
// jwt = base64(header).base64(payload).Signature
// Signature = HS256(base64(header).base64(payload),signingKey)
type MyCustomClaims struct {
	Username string `json:"username"`
	jwt.RegisteredClaims
}

// GenToken 生产jwt
func GenToken(username string) string {
	mySigningKey := []byte(config.JwtSecret)
	// Create claims with multiple fields populated
	claims := MyCustomClaims{
		username,
		jwt.RegisteredClaims{
			// A usual scenario is to set the expiration time relative to the current time
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(config.JwtExpire) * time.Minute)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
			Issuer:    "acy",
			Subject:   "login",
		},
	}
	//先生成前两个，header+payload
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	//根据base64的内容进行签名再拼接
	ss, err := token.SignedString(mySigningKey)
	if err != nil {
		panic(err)
	}
	return ss
}

// ParseToken 解析token
func ParseToken(tokenString string) (*MyCustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(config.JwtSecret), nil
	})
	if err != nil {
		log.Error(map[string]any{"error": err.Error()}, "解析token失败")
		return nil, err
	}
	if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
		return claims, nil
	} else {
		log.Warning(nil, "token已失效")
		return nil, errors.New("token已失效")
	}
}
